package pl.leader100.rest;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import pl.leader100.rest.data.Doc;
import pl.leader100.rest.data.DocDao;

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/listdocs")
public class ListDocs {
	private static final String year = "2011/2012";
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

	// private static final String course = "junior_leader_r1";

	@Context
	UriInfo uriInfo;
	@Context
	Request request;

	// This method is called if TEXT_PLAIN is request
	/*
	 * @GET
	 * 
	 * @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() {
	 * return "no way"; }
	 */

	// For the browser
	@GET
	@Produces(MediaType.TEXT_XML)
	public List<Doc> getDocsBrowser() {
		List<Doc> docs = new ArrayList<Doc>();
		docs.addAll(DocDao.GetInstance().getModel().values());
		return docs;
	}

	// Application integration
	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public List<Doc> getDoc() {
		List<Doc> docs = new ArrayList<Doc>();
		docs.addAll(DocDao.GetInstance().getModel().values());
		return docs;
	}

	// retuns the number of todos
	// Use http://localhost:8080/de.vogella.jersey.todo/rest/todos/count
	// to get the total number of records
	@GET
	@Path("count")
	@Produces(MediaType.TEXT_PLAIN)
	public String getCount() {
		int count = DocDao.GetInstance().getModel().size();
		return String.valueOf(count);
	}

	// Defines that the next path parameter after todos is
	// treated as a parameter and passed to the TodoResources
	// Allows to type http://localhost:8080/de.vogella.jersey.todo/rest/todos/1
	// 1 will be treaded as parameter todo and passed to Listdoc
	@Path("/role/{role}/date/{date}/locale/{locale}")
	// @Path("{role:(role/[^/]+?)?}{date:(date/[^/]+?)?}{locale:(locale/[^/]+?)?}")
	public ListDoc getDoc(@PathParam("role") String role,
			@PathParam("date") String date, @PathParam("locale") String locale) {
		if ("".equals(role))
			role = "*";
		else
			// role = role.split("/")[1];
			;
		if ("".equals(date))
			date = "*";
		else
			;// date = date.split("/")[1];

		if ("".equals(locale))
			locale = "*";
		else
			;// locale = locale.split("/")[1];
		return new ListDoc(uriInfo, request, role, date, locale);
	}

	@Path("/docs/{role}/{date}/{locale}/{course}")
	// @Path("{role:(role/[^/]+?)?}{date:(date/[^/]+?)?}{locale:(locale/[^/]+?)?}")
	public ListDoc getDoc(@PathParam("role") String role,
			@PathParam("date") String date, @PathParam("locale") String locale,
			@PathParam("course") String course) {
		if ("".equals(role))
			role = "*";
		else
			// role = role.split("/")[1];
			;
		if ("".equals(date))
			date = "*";
		else
			;// date = date.split("/")[1];

		if ("".equals(locale))
			locale = "*";
		else
			;// locale = locale.split("/")[1];
		return new ListDoc(uriInfo, request, role, date, locale, year, course);
	}

	@Path("/docs/{role}/{date}/{locale}/{course}/{category}")
	public ListDocByCat getDocByCat(@PathParam("role") String role,
			@PathParam("date") String date, @PathParam("locale") String locale,
			@PathParam("course") String course,
			@PathParam("category") String category) {
		if ("".equals(role))
			role = "*";
		else
			;
		if ("".equals(date))
			date = "*";
		else
			;
		if ("".equals(locale))
			locale = "*";
		else
			;
		if ("".equals(category))
			category = "*";
		else
			;
		return new ListDocByCat(uriInfo, request, role, date, locale, year,
				course, category);
	}

	@Path("/docs3/{role}/{date}/{locale}/{course}/{category}")
	public ListDocByCat3 getDocByCat3(@PathParam("role") String role,
			@PathParam("date") String date, @PathParam("locale") String locale,
			@PathParam("course") String course,
			@PathParam("category") String category) {
		if ("".equals(role))
			role = "*";
		else
			;
		if ("".equals(date))
			date = "*";
		else
			;

		if ("".equals(locale))
			locale = "*";
		else
			;
		if ("".equals(category))
			category = "*";
		else
			;
		return new ListDocByCat3(uriInfo, request, role, date, locale, year,
				course, category);
	}

	@Path("/situation/{month}/{locale}/{course}")
	public ListSituation getSituation(@PathParam("month") String month,
			@PathParam("locale") String locale,
			@PathParam("course") String course) {

		if ("".equals(month))
			month = "*";
		else
			;// date = date.split("/")[1];

		if ("".equals(locale))
			locale = "*";
		else
			;// locale = locale.split("/")[1];
		return new ListSituation(uriInfo, request, month, locale, "2011/2012",
				course);
	}

	@GET
	@Produces(MediaType.TEXT_HTML)
	@Path("/links/{role}/{date}/{locale}/{course}")
	public String getLinks(@PathParam("role") String role,
			@PathParam("date") String date, @PathParam("locale") String locale,
			@PathParam("course") String course) {
		if ("".equals(role))
			role = "*";
		else
			;
		if ("".equals(date))
			date = "*";
		else
			;

		if ("".equals(locale))
			locale = "*";
		else
			;

		List<Doc> docs = DocDao.GetInstance().getDocsOld(role, date, locale,
				year, course);
		if (docs == null)
			throw new RuntimeException("Get: Doc with " + role + " " + date
					+ " " + locale + " not found");

		String links = "<div class='l100_links'>";

		String prefix = "l100rest/rest/";

		for (Doc doc : docs) {
			String link = prefix + "listdocs/doc/" + doc.getId() + "/"
					+ doc.getUniqueKey();
			String name = doc.getTitle();
			links += "<a href='" + link + "' target='_new'>" + name
					+ "</a><br>";
		}
		links += "</div>";
		return links;
	}

	@GET
	@Produces(MediaType.TEXT_HTML)
	@Path("/links/{role}/{date}/{locale}/{course}/{category}")
	public String getLinks(@PathParam("role") String role,
			@PathParam("date") String date, @PathParam("locale") String locale,
			@PathParam("course") String course,
			@PathParam("category") String category) {
		if ("".equals(role))
			role = "*";
		else
			;
		if ("".equals(date))
			date = "*";
		else
			;

		if ("".equals(locale))
			locale = "*";
		else
			;
		if ("".equals(category))
			category = "*";
		else
			;

		List<Doc> docs = DocDao.GetInstance().getDocsByCat(role, date, locale,
				year, course, category);
		if (docs == null)
			throw new RuntimeException("Get: Doc with " + role + " " + date
					+ " " + locale + " not found");

		String links = "<div class='l100_links'>";

		String prefix = "l100rest/rest/";

		for (Doc doc : docs) {
			String link = prefix + "listdocs/doc/" + doc.getId() + "/"
					+ doc.getUniqueKey();
			String name = doc.getTitle();
			links += "<a href='" + link + "' target='_new'>" + name
					+ "</a><br>";
		}
		links += "</div>";
		return links;
	}

	@GET
	@Produces(MediaType.TEXT_HTML)
	@Path("/links3/{role}/{date}/{locale}/{course}/{category}")
	public String getLinks3(@PathParam("role") String role,
			@PathParam("date") String date, @PathParam("locale") String locale,
			@PathParam("course") String course,
			@PathParam("category") String category) {

		int m0, m1, m2;

		if ("".equals(role))
			role = "*";
		if ("".equals(date))
			date = "*";

		if ("".equals(locale))
			locale = "*";
		if ("".equals(category))
			category = "*";

		try {
			Date d;
			d = df.parse(date);
			Calendar cal = Calendar.getInstance();
			cal.setTime(d);

			// if (cal.get(Calendar.DATE)>=23) {
			// cal.add(Calendar.MONTH, +1);
			// }
			// Calendar.Month begin at 0, finish at 11
			m1 = cal.get(Calendar.MONTH) + 1;
			cal.add(Calendar.MONTH, -1);
			m0 = cal.get(Calendar.MONTH) + 1;
			cal.add(Calendar.MONTH, +2);
			m2 = cal.get(Calendar.MONTH) + 1;

			String links = "";// <div class='l100_links'>";

			links += "<td class='l100_prevLinks'>";
			links += addLinks(role, m0, locale, course, category);
			links += "</td>";
			links += "<td class='l100_actualLinks'>";
			links += addLinks(role, m1, locale, course, category);
			links += "</td>";
			links += "<td class='l100_nextLinks'>";
			links += addLinks(role, m2, locale, course, category);
			links += "</td>";

			links += "";// </div>";
			return links;
		} catch (Exception e) {
		}
		return null;
	}

	private String addLinks(String role, int month, String locale,
			String course, String category) {
		
		String hostport = "http://"+uriInfo.getAbsolutePath().getHost() + ":"
				+ uriInfo.getAbsolutePath().getPort();
		String prefix = hostport + "/l100rest/rest/";
		String links = "";

		List<Doc> docs = DocDao.GetInstance().getDocsByCat(role, month, locale,
				course, category);
		if (docs == null)
			throw new RuntimeException("Get: Doc with " + role + " " + month
					+ " " + locale + " not found");

		for (Doc doc : docs) {
			String link = prefix + "listdocs/doc/" + doc.getId() + "/"
					+ doc.getUniqueKey();
			String name = doc.getTitle();
			links += "<a href='" + link + "' target='_blank'>" + name
					+ "</a><br><br>";
		}
		return links;
	}

	private String addLinks(String role, String date, String locale,
			String course, String category) {

		String prefix = "l100rest/rest/";
		String links = "";
		List<Doc> docs = DocDao.GetInstance().getDocsByCat(role, date, locale,
				year, course, category);
		if (docs == null)
			throw new RuntimeException("Get: Doc with " + role + " " + date
					+ " " + locale + " not found");

		for (Doc doc : docs) {
			String link = prefix + "listdocs/doc/" + doc.getId() + "/"
					+ doc.getUniqueKey();
			String name = doc.getTitle();
			links += "<a href='" + link + "' target='_blank'>" + name
					+ "</a><br><br>";
		}
		return links;
	}

	/*
	 * @Path("/path/{locale}/{course}/{path}/{key}")
	 * 
	 * public RetrieveDoc retrieveDoc(@PathParam("locale") String locale,
	 * 
	 * @PathParam("course") String course, @PathParam("path") String path,
	 * 
	 * @PathParam("key") String key) {
	 * 
	 * if (DocDao.GetInstance().isKeyAvailable(key)) return new
	 * RetrieveDoc(uriInfo, request, locale, course, path); else { return null;
	 * } }
	 */

	@Path("/doc/{id}/{key}")
	public RetrieveDoc retrieveDocById(@PathParam("id") String id,
			@PathParam("key") String key) {
		
		Doc doc = DocDao.GetInstance().getDocByIdKey(id, key);
		String fileName = doc.getPath();
		
		int dotposition= fileName.lastIndexOf(".");
		String ext = fileName.substring(dotposition + 1, fileName.length()); 
		
		if (doc == null)
			return null;
		if(ext.equals(new String("html"))) {
			RetrieveDocHTML out = new RetrieveDocHTML(uriInfo, request, doc.getLocale(),
										doc.getCourse(), doc.getPath(), doc.getMimetype());
			return (RetrieveDoc)out;
		}
		else if(ext.equals(new String("pdf"))){
				RetrieveDocPDF out = new RetrieveDocPDF(uriInfo, request, doc.getLocale(), 
											doc.getCourse(), doc.getPath(), doc.getMimetype()); 
				return (RetrieveDoc)out;
		}
		return null;
	}
	}
